/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */
package org.jaxson.struts.encoder.excel;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Class to parse and store renders for classes which may be rendered as Excel.
 * 
 * @author Joe Maisel
 */
public class ExcelAnnotationCache
{
	private static final Log lager = LogFactory.getLog(ExcelAnnotationCache.class);
	private static final Map<Class<?>, ExcelFieldDescriptor> excelClasses = new HashMap<Class<?>, ExcelFieldDescriptor>();
	
	public static class ExcelFieldDescriptor
	{
		public List<String> getters;
		public Class<? extends ExcelRenderer> renderer;
		
		protected ExcelFieldDescriptor(List<String> getters, Class<? extends ExcelRenderer> renderer)
		{
			this.getters = getters;
			this.renderer = renderer;
		}
	}
	
	public static ExcelFieldDescriptor get( Class<?> cls )
	{
		return excelClasses.get(cls);
	}
	
	public static void parse( Class<?> cls ) throws SecurityException, NoSuchMethodException
	{
		lager.debug( "parsing class " + cls );
		List<String> getters = new ArrayList<String>();
		ExcelData a = (ExcelData)cls.getAnnotation( ExcelData.class );
		Class<? extends ExcelRenderer> renderer = a.renderer() == null?DefaultExcelRenderer.class:a.renderer();
		
		for( Method m : cls.getDeclaredMethods() )
		{
			if( m.getName().startsWith( "get" ) && m.getParameterTypes().length == 0 && !m.getReturnType().equals( Void.class ) )
			{
				getters.add( m.getName() );
			}
		}
		excelClasses.put( cls, new ExcelFieldDescriptor(getters, renderer) );
	}
}
